package com.example.shop.mine

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.UserEntity
import com.example.base.mvvm.BaseFragment
import com.example.shop.R
import com.example.shop.databinding.FragmentMineBinding
import com.example.shop.db.AppDbUtils
import com.example.shop.utils.GlideUtils
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class MineFragment : BaseFragment<FragmentMineBinding,MineViewModel>() {
    lateinit var user:UserEntity
    override fun initView() {

        user = AppDbUtils.getAppDb().getUserDao().selectById(SPUtils.getInstance().getString("username"))
        binding.user = user
        binding.btnLogout.setOnClickListener {
            //跳转到登录界面
            //清空spUtils中的记录
            SPUtils.getInstance().clear()
            ARouter.getInstance().build("/app/MainActivity").navigation()
        }
        //点击修改头像、地址
        binding.tvAddress.setOnClickListener {
            val addressPicker = AddressPicker(requireActivity())
            addressPicker.setTitle("请选择配送地址")
            addressPicker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)//三级联动的效果
            addressPicker.setOnAddressPickedListener { province, city, county ->
                binding.tvAddress.text = "${province.name}${city.name}${county.name}"//显示页面
                viewModel.address("${province.name}${city.name}${county.name}")//调用后台
            }
            addressPicker.show()
        }
        binding.ivUser.setOnClickListener {
            PictureSelector.create(this,103).selectPicture()
        }

        val navHostFragment = childFragmentManager.findFragmentById(R.id.fragmentContainerView2) as NavHostFragment
        val navController = navHostFragment.navController
        binding.botMine.setupWithNavController(navController)

    }

    override fun initData() {
        viewModel.addressSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                user.address = it.data.toString()
                AppDbUtils.getAppDb().getUserDao().updateUser(user)//更新数据库的记录
            }
        }
        viewModel.iconSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                user.icon = it.data.toString()
                AppDbUtils.getAppDb().getUserDao().updateUser(user)
            }
        }
    }

    override fun getViewModel(): Class<MineViewModel> = MineViewModel::class.java

    override fun getLayout(): Int  = R.layout.fragment_mine

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==103&&resultCode==Activity.RESULT_OK){
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            GlideUtils.loadCircleImage(requireContext(),pictureBean.path,binding.ivUser)
            val body = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), File(pictureBean.path))
            val part = MultipartBody.Part.createFormData("file","abc.jpg",body)
            viewModel.updateIcon(part)
        }
    }

}